// ===== 管理员仪表板系统 =====

let dashboardData = {};
let chartInstances = {};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadDashboardData();
    updateStatistics();
    initializeCharts();
    loadRecentFeedbacks();
    loadActivityLogs();
    setupEventListeners();
    startDataRefresh();
});

// ===== 数据加载和处理 =====

function loadDashboardData() {
    try {
        // 加载反馈数据
        const feedbackData = localStorage.getItem('modFeedbacks');
        const feedbacks = feedbackData ? JSON.parse(feedbackData) : [];
        
        // 生成模拟数据
        dashboardData = {
            feedbacks: feedbacks,
            downloads: generateDownloadData(),
            users: generateUserData(),
            systemStatus: getSystemStatus()
        };
        
        console.log('仪表板数据已加载:', dashboardData);
    } catch (error) {
        console.error('加载仪表板数据失败:', error);
        dashboardData = {
            feedbacks: [],
            downloads: [],
            users: [],
            systemStatus: {}
        };
    }
}

function generateDownloadData() {
    const data = [];
    const baseDate = new Date();
    baseDate.setDate(baseDate.getDate() - 30);
    
    for (let i = 0; i < 30; i++) {
        const date = new Date(baseDate);
        date.setDate(date.getDate() + i);
        
        data.push({
            date: date.toISOString().split('T')[0],
            downloads: Math.floor(Math.random() * 50) + 20,
            newUsers: Math.floor(Math.random() * 15) + 5
        });
    }
    
    return data;
}

function generateUserData() {
    return {
        total: 856,
        active: 623,
        new: 43,
        returning: 580
    };
}

function getSystemStatus() {
    return {
        uptime: '15天 8小时 32分钟',
        memoryUsage: Math.floor(Math.random() * 30) + 60,
        storageUsage: Math.floor(Math.random() * 20) + 15,
        activeConnections: Math.floor(Math.random() * 100) + 200
    };
}

// ===== 统计数据更新 =====

function updateStatistics() {
    const feedbacks = dashboardData.feedbacks;
    const downloads = dashboardData.downloads;
    
    // 计算总下载量
    const totalDownloads = downloads.reduce((sum, day) => sum + day.downloads, 0) + 1000;
    updateStatElement('totalDownloads', totalDownloads);
    
    // 活跃用户数
    updateStatElement('activeUsers', dashboardData.users.active);
    
    // 待处理反馈
    const pendingFeedbacks = feedbacks.length;
    updateStatElement('pendingFeedbacks', pendingFeedbacks);
    
    // 平均评分（模拟）
    const averageRating = (Math.random() * 0.5 + 4.5).toFixed(1);
    updateStatElement('averageRating', averageRating);
    
    // 更新反馈计数徽章
    document.getElementById('feedbackCount').textContent = pendingFeedbacks;
    
    // 添加数字动画
    animateNumbers();
}

function updateStatElement(id, value) {
    const element = document.getElementById(id);
    if (element) {
        element.textContent = typeof value === 'number' ? value.toLocaleString() : value;
    }
}

function animateNumbers() {
    const counters = document.querySelectorAll('.stat-info h3');
    counters.forEach(counter => {
        const target = parseFloat(counter.textContent.replace(/,/g, ''));
        if (isNaN(target)) return;
        
        const increment = Math.max(1, Math.floor(target / 30));
        let current = 0;
        
        const updateCounter = () => {
            if (current < target) {
                current = Math.min(current + increment, target);
                counter.textContent = current.toLocaleString();
                requestAnimationFrame(updateCounter);
            }
        };
        
        counter.textContent = '0';
        setTimeout(updateCounter, 200);
    });
}

// ===== 图表初始化 =====

function initializeCharts() {
    initDownloadChart();
    initFeedbackChart();
}

function initDownloadChart() {
    const ctx = document.getElementById('downloadChart');
    if (!ctx) return;
    
    const downloadData = dashboardData.downloads;
    const labels = downloadData.map(d => {
        const date = new Date(d.date);
        return `${date.getMonth() + 1}/${date.getDate()}`;
    });
    const downloads = downloadData.map(d => d.downloads);
    
    if (chartInstances.downloadChart) {
        chartInstances.downloadChart.destroy();
    }
    
    chartInstances.downloadChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: '每日下载量',
                data: downloads,
                borderColor: '#4ade80',
                backgroundColor: 'rgba(74, 222, 128, 0.1)',
                borderWidth: 3,
                fill: true,
                tension: 0.4,
                pointBackgroundColor: '#4ade80',
                pointBorderColor: '#ffffff',
                pointBorderWidth: 2,
                pointRadius: 5,
                pointHoverRadius: 8
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                intersect: false,
                mode: 'index'
            },
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                x: {
                    display: true,
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    },
                    ticks: {
                        color: 'rgba(255, 255, 255, 0.7)',
                        maxTicksLimit: 8
                    }
                },
                y: {
                    display: true,
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    },
                    ticks: {
                        color: 'rgba(255, 255, 255, 0.7)'
                    }
                }
            }
        }
    });
}

function initFeedbackChart() {
    const ctx = document.getElementById('feedbackChart');
    if (!ctx) return;
    
    const feedbacks = dashboardData.feedbacks;
    const feedbackTypes = {
        'bug': 0,
        'feature': 0,
        'compatibility': 0,
        'other': 0
    };
    
    feedbacks.forEach(feedback => {
        if (feedbackTypes.hasOwnProperty(feedback.type)) {
            feedbackTypes[feedback.type]++;
        }
    });
    
    if (chartInstances.feedbackChart) {
        chartInstances.feedbackChart.destroy();
    }
    
    chartInstances.feedbackChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['Bug报告', '功能建议', '兼容性问题', '其他问题'],
            datasets: [{
                data: [
                    feedbackTypes.bug,
                    feedbackTypes.feature,
                    feedbackTypes.compatibility,
                    feedbackTypes.other
                ],
                backgroundColor: [
                    '#ef4444',
                    '#22c55e',
                    '#f59e0b',
                    '#8b5cf6'
                ],
                borderWidth: 0,
                hoverBorderWidth: 3,
                hoverBorderColor: '#ffffff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: 'rgba(255, 255, 255, 0.8)',
                        usePointStyle: true,
                        pointStyle: 'circle'
                    }
                }
            }
        }
    });
}

// ===== 最新反馈加载 =====

function loadRecentFeedbacks() {
    const feedbacks = dashboardData.feedbacks.slice(0, 5);
    const container = document.getElementById('recentFeedbacks');
    
    if (!container) return;
    
    if (feedbacks.length === 0) {
        container.innerHTML = `
            <div class="no-recent-data">
                <i class="fas fa-inbox"></i>
                <p>暂无最新反馈</p>
            </div>
        `;
        return;
    }
    
    container.innerHTML = feedbacks.map(feedback => {
        const date = new Date(feedback.timestamp);
        const timeAgo = getTimeAgo(date);
        const typeClass = getTypeClass(feedback.type);
        
        return `
            <div class="recent-item">
                <div class="recent-icon ${typeClass}">
                    <i class="fas fa-${getTypeIcon(feedback.type)}"></i>
                </div>
                <div class="recent-info">
                    <div class="recent-title">${escapeHtml(feedback.title)}</div>
                    <div class="recent-meta">
                        来自 ${escapeHtml(feedback.email)} · ${timeAgo}
                    </div>
                </div>
                <div class="recent-time">${timeAgo}</div>
            </div>
        `;
    }).join('');
}

function getTypeClass(type) {
    const typeMap = {
        'bug': 'bug',
        'feature': 'feature',
        'compatibility': 'other',
        'other': 'other'
    };
    return typeMap[type] || 'other';
}

function getTypeIcon(type) {
    const iconMap = {
        'bug': 'bug',
        'feature': 'lightbulb',
        'compatibility': 'puzzle-piece',
        'other': 'question-circle'
    };
    return iconMap[type] || 'question-circle';
}

function getTimeAgo(date) {
    const now = new Date();
    const diffInSeconds = Math.floor((now - date) / 1000);
    
    if (diffInSeconds < 60) return '刚刚';
    if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}分钟前`;
    if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}小时前`;
    if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)}天前`;
    
    return date.toLocaleDateString('zh-CN');
}

// ===== 活动日志 =====

function loadActivityLogs() {
    const logs = generateActivityLogs();
    const container = document.getElementById('activityLogs');
    
    if (!container) return;
    
    container.innerHTML = logs.map(log => `
        <div class="log-item">
            <div class="log-time">${log.time}</div>
            <div class="log-icon ${log.type}"></div>
            <div class="log-content">${log.message}</div>
        </div>
    `).join('');
}

function generateActivityLogs() {
    const logs = [
        { time: '10:32', type: 'success', message: '用户反馈处理完成 - Bug #1234' },
        { time: '10:15', type: 'info', message: '新用户注册: user@example.com' },
        { time: '09:45', type: 'warning', message: '系统内存使用率达到 85%' },
        { time: '09:30', type: 'success', message: '数据备份完成' },
        { time: '09:15', type: 'info', message: '新反馈提交: 功能建议' },
        { time: '08:50', type: 'error', message: '下载服务器响应延迟' },
        { time: '08:30', type: 'success', message: '系统启动完成' },
        { time: '08:00', type: 'info', message: '开始执行日常维护任务' }
    ];
    
    return logs;
}

// ===== 事件处理 =====

function setupEventListeners() {
    // 下载时间段切换
    const downloadPeriod = document.getElementById('downloadPeriod');
    if (downloadPeriod) {
        downloadPeriod.addEventListener('change', function() {
            updateDownloadChart(this.value);
        });
    }
}

function updateDownloadChart(period) {
    // 根据时间段更新图表数据
    let dataPoints;
    
    switch (period) {
        case '7d':
            dataPoints = 7;
            break;
        case '30d':
            dataPoints = 30;
            break;
        case '90d':
            dataPoints = 90;
            break;
        default:
            dataPoints = 30;
    }
    
    // 重新生成数据并更新图表
    dashboardData.downloads = generateDownloadDataForPeriod(dataPoints);
    initDownloadChart();
    
    showNotification(`图表已更新为最近${dataPoints}天的数据`, 'success');
}

function generateDownloadDataForPeriod(days) {
    const data = [];
    const baseDate = new Date();
    baseDate.setDate(baseDate.getDate() - days);
    
    for (let i = 0; i < days; i++) {
        const date = new Date(baseDate);
        date.setDate(date.getDate() + i);
        
        data.push({
            date: date.toISOString().split('T')[0],
            downloads: Math.floor(Math.random() * 50) + 20,
            newUsers: Math.floor(Math.random() * 15) + 5
        });
    }
    
    return data;
}

// ===== 快速操作 =====

function exportData() {
    showNotification('正在导出数据...', 'info');
    
    const exportData = {
        feedbacks: dashboardData.feedbacks,
        statistics: {
            totalDownloads: document.getElementById('totalDownloads').textContent,
            activeUsers: document.getElementById('activeUsers').textContent,
            pendingFeedbacks: document.getElementById('pendingFeedbacks').textContent,
            averageRating: document.getElementById('averageRating').textContent
        },
        downloads: dashboardData.downloads,
        exportDate: new Date().toISOString()
    };
    
    const blob = new Blob([JSON.stringify(exportData, null, 2)], { 
        type: 'application/json' 
    });
    const url = URL.createObjectURL(blob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = `dashboard-export-${new Date().toISOString().split('T')[0]}.json`;
    link.style.display = 'none';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    URL.revokeObjectURL(url);
    
    setTimeout(() => {
        showNotification('数据导出完成', 'success');
    }, 1500);
}

function backupData() {
    showNotification('正在创建备份...', 'info');
    
    setTimeout(() => {
        showNotification('数据备份完成', 'success');
        updateActivityLog('数据备份完成', 'success');
    }, 2000);
}

function clearCache() {
    if (confirm('确定要清除所有缓存吗？这可能会影响页面加载速度。')) {
        showNotification('正在清除缓存...', 'info');
        
        // 清除部分localStorage（保留重要数据）
        const keysToKeep = ['modFeedbacks', 'adminSettings'];
        const allKeys = Object.keys(localStorage);
        
        allKeys.forEach(key => {
            if (!keysToKeep.includes(key)) {
                localStorage.removeItem(key);
            }
        });
        
        setTimeout(() => {
            showNotification('缓存清除完成', 'success');
            updateActivityLog('系统缓存已清理', 'success');
        }, 1500);
    }
}

function sendNotification() {
    const message = prompt('请输入要发送的通知内容:');
    if (message && message.trim()) {
        showNotification('正在发送通知...', 'info');
        
        setTimeout(() => {
            showNotification('通知发送成功', 'success');
            updateActivityLog(`系统通知已发送: ${message.substring(0, 20)}...`, 'info');
        }, 1500);
    }
}

function updateActivityLog(message, type) {
    const container = document.getElementById('activityLogs');
    if (!container) return;
    
    const now = new Date();
    const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
    
    const newLog = document.createElement('div');
    newLog.className = 'log-item';
    newLog.innerHTML = `
        <div class="log-time">${time}</div>
        <div class="log-icon ${type}"></div>
        <div class="log-content">${message}</div>
    `;
    
    container.insertBefore(newLog, container.firstChild);
    
    // 限制日志数量
    const logs = container.querySelectorAll('.log-item');
    if (logs.length > 20) {
        container.removeChild(logs[logs.length - 1]);
    }
}

function refreshLogs() {
    showNotification('正在刷新活动日志...', 'info');
    
    setTimeout(() => {
        loadActivityLogs();
        showNotification('活动日志已刷新', 'success');
    }, 1000);
}

// ===== 数据自动刷新 =====

function startDataRefresh() {
    // 每30秒刷新一次统计数据
    setInterval(() => {
        updateStatistics();
        updateSystemStatus();
    }, 30000);
    
    // 每5分钟刷新一次反馈数据
    setInterval(() => {
        loadDashboardData();
        loadRecentFeedbacks();
        updateStatistics();
    }, 300000);
}

function updateSystemStatus() {
    // 模拟系统状态更新
    dashboardData.systemStatus = getSystemStatus();
    
    // 如果内存使用率过高，添加警告日志
    if (dashboardData.systemStatus.memoryUsage > 85) {
        updateActivityLog(`系统内存使用率: ${dashboardData.systemStatus.memoryUsage}%`, 'warning');
    }
}

// ===== 侧边栏管理 =====

function toggleSidebar() {
    const sidebar = document.querySelector('.admin-sidebar');
    if (sidebar) {
        sidebar.classList.toggle('show');
    }
}

function logout() {
    if (confirm('确定要退出登录吗？')) {
        showNotification('正在退出...', 'info');
        setTimeout(() => {
            window.location.href = 'index.html';
        }, 1000);
    }
}

// ===== 工具函数 =====

function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check' : type === 'error' ? 'times' : type === 'warning' ? 'exclamation-triangle' : 'info-circle'}"></i>
        <span>${message}</span>
    `;
    
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#4ade80' : type === 'error' ? '#ef4444' : type === 'warning' ? '#f59e0b' : '#3b82f6'};
        color: white;
        padding: 15px 20px;
        border-radius: 10px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        z-index: 10000;
        display: flex;
        align-items: center;
        gap: 10px;
        font-weight: 500;
        transform: translateX(100%);
        transition: transform 0.3s ease;
        max-width: 300px;
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// ===== 响应式处理 =====

window.addEventListener('resize', function() {
    // 重新调整图表大小
    Object.values(chartInstances).forEach(chart => {
        if (chart && typeof chart.resize === 'function') {
            chart.resize();
        }
    });
});

// ===== 页面离开时清理 =====

window.addEventListener('beforeunload', function() {
    // 销毁图表实例
    Object.values(chartInstances).forEach(chart => {
        if (chart && typeof chart.destroy === 'function') {
            chart.destroy();
        }
    });
});